package com.itlong.cloud.controller.visitor;

import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.common.WeChatVisitorMsgDTO;
import com.itlong.cloud.POJO.DTO.sdk.VisitorServerGetListDTO;
import com.itlong.cloud.POJO.DTO.sdk.VisitorServerSubmitDTO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppCreateBaiduFaceVO;
import com.itlong.cloud.POJO.VO.operate.OperateFaceApplyInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.VisitorOperateTypeEnum;
import com.itlong.cloud.enumerate.ecode.*;
import com.itlong.cloud.equip.app.IAppVisitorPassCodeRecordServiceClient;
import com.itlong.cloud.equip.property.IPadFaceSyncDataServiceClient;
import com.itlong.cloud.iottp.IIotBaiduFaceServiceClient;
import com.itlong.cloud.iottp.IWeChatTemplateMsgServiceClient;
import com.itlong.cloud.user.sdk.IVisitorServerServiceClient;
import com.itlong.cloud.project.operate.IOperateFaceApplyServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * <desc>
 *      访客机SDK
 * </desc>
 *
 * @createDate 2019/04/29
 */
@RestController
@RequestMapping("/visitor/api")
@RefreshScope
public class VisitorServerServiceSDKController extends BaseController{
    private static final Logger LOG = LoggerFactory.getLogger(VisitorServerServiceSDKController.class);

    @Autowired
    IVisitorServerServiceClient iVisitorServerServiceClient;

    @Autowired
    IOperateFaceApplyServiceClient iOperateFaceApplyServiceClient;

    @Autowired
    IIotBaiduFaceServiceClient iIotBaiduFaceServiceClient;

    @Autowired
    IAppVisitorPassCodeRecordServiceClient iAppVisitorPassCodeRecordServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    IPadFaceSyncDataServiceClient iPadFaceSyncDataServiceClient;

    @Autowired
    IWeChatTemplateMsgServiceClient iWeChatTemplateMsgServiceClient;
    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;
    /**
     * <desc>
     *      获取项目的地址信息
     * </desc>
     *
     * @param appid
     * @param appsecret
     * @param projectId
     * @param buildId
     * @param unitId
     * @return
     * @author Jiaqi.X
     * @createDate 2019/04/29
     */
    @RequestMapping("getAddress")
    @ResponseBody
    public MessageVO getAddress(String appid,String appsecret,String projectId,String buildId,String unitId){
        try {
            if(StringUtils.isBlank(appid) || StringUtils.isBlank(appsecret)){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_IS_NULL.getErrorCode());
            }else if(StringUtils.isBlank(projectId)){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_PROJECTID_IS_ILLEGAL.getErrorCode());
            }
            //检测身份信息
            if (iVisitorServerServiceClient.checkIdentity(projectId, appid, appsecret) == 0) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iVisitorServerServiceClient.getAddressInfo(projectId,buildId,unitId));
        }catch (Exception e) {
            throw new DataAccessException("【访客机SDK_服务端】获取项目的地址信息失败", e);
        }
    }

    /**
     * <desc>
     *      提交访客单
     * </desc>
     *
     * @param dto
     * @return
     * @author Jiaqi.X
     * @createDate 2019/04/29
     */
    @RequestMapping("submit")
    @ResponseBody
    public MessageVO submit(VisitorServerSubmitDTO dto){
        try {
            if(StringUtils.isBlank(dto.getAppid()) || StringUtils.isBlank(dto.getAppsecret())){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_IS_NULL.getErrorCode());
            }else if(StringUtils.isBlank(dto.getProjectId())){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_PROJECTID_IS_ILLEGAL.getErrorCode());
            }
            //检测身份信息
            if (iVisitorServerServiceClient.checkIdentity(dto.getProjectId(), dto.getAppid(), dto.getAppsecret()) == 0) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(dto.getBuildId()) || StringUtils.isBlank(dto.getUnitId()) || StringUtils.isBlank(dto.getRoomId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Map<String,Object> resultMap = iVisitorServerServiceClient.submit(dto);
            if(resultMap!=null && resultMap.containsKey("errMsg")){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_ROOMID_ERR.getErrorCode());
            }
            if(StringUtils.isNotBlank(dto.getVisitorFacePic())) {
                Map<String, String> map = new HashMap<>();
                LOG.info(JsonUtil.toJSON(dto));
                String uploadFilePath = uploadImageFile(dto.getVisitorFacePic(), "png", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
                //判断项目是否开启人脸识别,并查询是否有百度库key
                OperateFaceApplyInfoVO operateFaceApplyInfoVO = iOperateFaceApplyServiceClient.getFaceByProjectId(dto.getProjectId());
                if (operateFaceApplyInfoVO == null) {
                    ErrorCode errorCode = AppErrorCodeEnum.PROJECT_FACE_APPID_INEXISTENCE.getErrorCode();
                    return new MessageVO(errorCode);
                }
                //访客人脸注册时,判断人脸库中是否有此人数据
                AppCreateBaiduFaceVO appCreateBaiduFaceVO = new AppCreateBaiduFaceVO();
                appCreateBaiduFaceVO.setAPP_ID(operateFaceApplyInfoVO.getAppId());
                appCreateBaiduFaceVO.setAPI_KEY(operateFaceApplyInfoVO.getApiKey());
                appCreateBaiduFaceVO.setSECRET_KEY(operateFaceApplyInfoVO.getSecretKey());
                appCreateBaiduFaceVO.setFaceScore(operateFaceApplyInfoVO.getFaceScore() == 0F ? 80F : operateFaceApplyInfoVO.getFaceScore());
//            String imageStr = URLDecoder.decode(dto.getVisitorFacePic(), "UTF-8");
//            appCreateBaiduFaceVO.setFile(new BASE64Decoder().decodeBuffer(imageStr));
                appCreateBaiduFaceVO.setImageUrl(uploadFilePath);
                String repeatResult = iIotBaiduFaceServiceClient.identifyUser(appCreateBaiduFaceVO);//拿到现有的id
                if (repeatResult != null && !"".equals(repeatResult)) {
                    if ("error".equals(repeatResult)) {//调用接口异常
                        return new MessageVO(PropertyErrorCodeEnum.APPUSER_IDENTIFY_ERROR.getErrorCode());
                    }
                    if ("busy".equals(repeatResult)) {//调用接口忙
                        return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode());
                    }
                }
                String vFaceId;
                //判断认证图片是否重复
                if (repeatResult == null) {//人脸库中无此人脸ID使用V_ + pass_id
                    appCreateBaiduFaceVO.setUid("V_" + resultMap.get("passId").toString());
                    //创建百度人脸信息
                    boolean result = iIotBaiduFaceServiceClient.doCreateBaiduFaceForVisitor(appCreateBaiduFaceVO);
                    if (!result) {
                        map.put("result", "2");
                        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
                    }
                    vFaceId = appCreateBaiduFaceVO.getUid();
                } else {//人脸库中有此人脸
                    //有此人脸时证明这个人在此项目中注册过人脸业主使用的是这个人的user_id,访客使用的是V_ + pass_id   不进行重复注册
                    if (repeatResult.substring(0, 2).equals("V_")) {//访客人脸则进行覆盖
                        appCreateBaiduFaceVO.setUid(repeatResult);
                        //创建百度人脸信息
                        boolean result = iIotBaiduFaceServiceClient.doCreateBaiduFaceForVisitor(appCreateBaiduFaceVO);
                        if (!result) {
                            map.put("result", "2");
                            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
                        }
                    }
                    vFaceId = repeatResult;
                }
                iAppVisitorPassCodeRecordServiceClient.setVisitPassFace(resultMap.get("passId").toString(), uploadFilePath, vFaceId, dto.getProjectId(), "", 0);

                Date currentTime = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                map.put("authDate", formatter.format(currentTime));
                map.put("result", "1");
            }
            //查询当前项目信息
            ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(dto.getProjectId());
            // 平板优先离线，则插入同步数据
            if (projectPO.getOnOffLinePadFace() != null) {
                PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                padFaceSyncDataDTO.setOperateType("3");
                padFaceSyncDataDTO.setProjectId(dto.getProjectId());
                padFaceSyncDataDTO.setPassId(resultMap.get("passId").toString());
                padFaceSyncDataDTO.setStatus("1");
                padFaceSyncDataDTO.setSourceSystem(4);
                if(projectPO.getOnOffLinePadFace() == 1){
                    iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
                }
                iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),resultMap.get("accessPath"));
        }catch (Exception e) {
            throw new DataAccessException("【访客机SDK_服务端】提交访客单失败", e);
        }
    }

    /**
     * <desc>
     *      上传图片文件
     * <desc/>
     *
     * @param imageStr 图片二进制
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-07
     */
    private String uploadImageFile(String imageStr,String imageType, FileCatalogEnum fileCatalog){
        byte[] bytes = null;
        try {
            bytes = new BASE64Decoder().decodeBuffer(imageStr);
        } catch (IOException e) {
            LOG.info("BASE64Decoder().decodeBuffer失败,imageStr不合法", e);
            return null;
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );
        try {
            //LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)){
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            }else {
                LOG.info(String.format("图片上传失败，returnCode: %s",returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }

    /**
     * <desc>
     *      获取访客列表
     * </desc>
     *
     * @param dto
     * @return
     * @author Jiaqi.X
     * @createDate 2019/04/29
     */
    @RequestMapping("getList")
    @ResponseBody
    public MessageVO getList(VisitorServerGetListDTO dto){
        try {
            if(StringUtils.isBlank(dto.getAppid()) || StringUtils.isBlank(dto.getAppsecret())){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_IS_NULL.getErrorCode());
            }else if(StringUtils.isBlank(dto.getProjectId())){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_PROJECTID_IS_ILLEGAL.getErrorCode());
            }
            //检测身份信息
            if (iVisitorServerServiceClient.checkIdentity(dto.getProjectId(), dto.getAppid(), dto.getAppsecret()) == 0) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iVisitorServerServiceClient.getList(dto));
        }catch (Exception e) {
            throw new DataAccessException("【访客机SDK_服务端】获取访客列表失败", e);
        }
    }

    /**
     * <desc>
     *      审批
     * </desc>
     *
     * @param appid
     * @param appsecret
     * @param projectId
     * @param visitorNo
     * @return
     * @author Jiaqi.X
     * @createDate 2019/04/29
     */
    @RequestMapping("approve")
    @ResponseBody
    public MessageVO approve(String appid,String appsecret,String projectId,String visitorNo){
        try {
            if(StringUtils.isBlank(appid) || StringUtils.isBlank(appsecret)){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_IS_NULL.getErrorCode());
            }else if(StringUtils.isBlank(projectId)){
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_PROJECTID_IS_ILLEGAL.getErrorCode());
            }
            //检测身份信息
            if (iVisitorServerServiceClient.checkIdentity(projectId, appid, appsecret) == 0) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_ERR.getErrorCode());
            }
            String passId = iVisitorServerServiceClient.approve(projectId,visitorNo);
            WeChatVisitorMsgDTO msgDTO = new WeChatVisitorMsgDTO();
            msgDTO.setOperateType(VisitorOperateTypeEnum.PROPERTY_CHECK_PASS.getType().toString());
            msgDTO.setPassId(passId);
            iWeChatTemplateMsgServiceClient.sendWeChatTemplateMsg(msgDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e) {
            throw new DataAccessException("【访客机SDK_服务端】获取访客列表失败", e);
        }
    }
}
